import Reflux from 'reflux';
import PageConst from './PageConst';
import Actions from './Actions';
import update from 'react-addons-update';
import DB from '../../../app/db';

export default Reflux.createStore({
  listenables: [Actions],
  data: {
    ...PageConst,
    searchText: '',
    searchDivShow: false,
    pdata: {},
    searchData: [],
  },

  onHandleSubmit: function (text) {

    let that = this;

    text = text.replace(/(^\s+)|(\s+$)/g, "");

    that.data = update(that.data, {
      searchDivShow: {$set: true},

    });

    if ("" != text && null != text) {

      DB.WechatAPI.searchSuggest({page: 1, size: 30, text: text}).then(
        function (content) {
          that.data = update(that.data, {
            searchDivShow: {$set: true},
            searchData: {$set: content.content}
          });
          that.updateComponent();
        },
        function (error) {
          console.log(error);
        }
      );
    }
  },

  onHandleCancel: function () {
    this.data.searchDivShow = update(this.data.searchDivShow, {$set: false});
    this.updateComponent();
  },

  onLoadData: function (resolve) {
    let that = this;
    DB.WechatAPI.loadLastSuggestionOneByType().then(
      function (content) {
        console.log(content);
        that.data.pdata = update(that.data.pdata, {$set: content});
        that.updateComponent();
        if (resolve) {
          resolve();
        }
      },
      function (error) {
        console.log(error);
      }
    );
  },

  updateComponent: function () {
    this.trigger(this.data);
  },

  getInitialState: function () {
    return this.data;
  }
});
